{% extends 'base.html' %}

{% block title %}自动发现设备 - Allen监控系统{% endblock %}

{% block content %}
<div class="container">
    <h2>自动发现设备</h2>
    
    <form id="discoverForm" class="mb-4">
        {% csrf_token %}
        <div class="form-group">
            <label for="network">网段</label>
            <input type="text" class="form-control" id="network" name="network" 
                   placeholder="例如: 192.168.1.0/24" required>
        </div>
        <button type="submit" class="btn btn-primary mt-2">开始发现</button>
    </form>

    <div id="taskStatus" class="mt-4" style="display: none;">
        <h6>当前任务状态：</h6>
        <div class="alert" role="alert"></div>
        
        <!-- 添加进度条 -->
        <div class="progress" style="height: 20px;">
            <div class="progress-bar progress-bar-striped progress-bar-animated" 
                 role="progressbar" 
                 aria-valuenow="0" 
                 aria-valuemin="0" 
                 aria-valuemax="100" 
                 style="width: 0%">
                <span class="progress-text">0%</span>
            </div>
        </div>
    </div>

    <h3>任务列表</h3>
    <div id="taskList">
        {% for task_id, task in recent_tasks.items %}
        <div id="task-{{ task_id }}" class="task-row">
            <span>网段: {{ task.kwargs.network }}</span>
            <span class="task-status {% if task.status == 'completed' %}text-success
                                    {% elif task.status == 'failed' %}text-danger
                                    {% elif task.status == 'running' %}text-primary
                                    {% else %}text-warning{% endif %}">
                {{ task.status }}
            </span>
            {% if task.status == 'running' or task.status == 'pending' %}
            <button class="btn btn-sm btn-danger cancel-task" data-task-id="{{ task_id }}">
                取消
            </button>
            {% endif %}
        </div>
        {% endfor %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    let progressInterval;

    $('#discoverForm').on('submit', function(e) {
        e.preventDefault();
        
        // 重置进度条
        resetProgress();
        
        $.ajax({
            url: '{% url "auto_discover" %}',
            method: 'POST',
            data: $(this).serialize(),
            success: function(response) {
                if (response.status === 'success') {
                    $('#taskStatus').show()
                        .find('.alert')
                        .removeClass('alert-danger')
                        .addClass('alert-info')
                        .text('任务已启动，正在执行...');
                    
                    // 开始轮询任务状态
                    pollTaskStatus(response.task_id);
                    // 启动进度条动画
                    startProgressAnimation();
                }
            },
            error: function(xhr) {
                $('#taskStatus').show()
                    .find('.alert')
                    .removeClass('alert-info')
                    .addClass('alert-danger')
                    .text('任务启动失败：' + (xhr.responseJSON?.message || '未知错误'));
            }
        });
    });
    
    function resetProgress() {
        clearInterval(progressInterval);
        const $progressBar = $('.progress-bar');
        $progressBar.css('width', '0%')
                   .attr('aria-valuenow', 0)
                   .find('.progress-text').text('0%');
    }

    function startProgressAnimation() {
        let progress = 0;
        const $progressBar = $('.progress-bar');
        
        progressInterval = setInterval(() => {
            // 使用非线性进度增长
            if (progress < 90) {
                progress += (90 - progress) * 0.1;
                const currentProgress = Math.min(Math.round(progress), 90);
                
                $progressBar.css('width', currentProgress + '%')
                           .attr('aria-valuenow', currentProgress)
                           .find('.progress-text').text(currentProgress + '%');
            }
        }, 1000);
    }
    
    function completeProgress() {
        clearInterval(progressInterval);
        const $progressBar = $('.progress-bar');
        
        $progressBar.removeClass('progress-bar-animated')
                   .css('width', '100%')
                   .attr('aria-valuenow', 100)
                   .find('.progress-text').text('100%');
    }
    
    function pollTaskStatus(taskId) {
        function checkStatus() {
            $.ajax({
                url: "{% url 'task_status' task_id='placeholder' %}".replace('placeholder', taskId),
                type: 'GET',
                success: function(response) {
                    let alertDiv = $('#taskStatus .alert');
                    
                    switch(response.status) {
                        case 'completed':
                            alertDiv.removeClass('alert-info')
                                   .addClass('alert-success')
                                   .text(`发现完成！发现了 ${response.result.length} 个设备`);
                            completeProgress();
                            setTimeout(function() {
                                window.location.reload();
                            }, 2000);
                            break;
                            
                        case 'failed':
                            alertDiv.removeClass('alert-info')
                                   .addClass('alert-danger')
                                   .text('任务失败：' + response.error);
                            clearInterval(progressInterval);
                            $('.progress-bar').addClass('bg-danger');
                            break;
                            
                        case 'running':
                            if (response.progress) {
                                // 如果后端提供了进度信息，更新进度条
                                updateProgress(response.progress);
                            }
                            setTimeout(checkStatus, 2000);
                            break;
                            
                        case 'pending':
                            alertDiv.removeClass('alert-danger alert-success')
                                   .addClass('alert-info')
                                   .text('任务正在准备中...');
                            setTimeout(checkStatus, 2000);
                            break;
                            
                        default:
                            alertDiv.removeClass('alert-info')
                                   .addClass('alert-warning')
                                   .text('未知状态：' + response.status);
                            clearInterval(progressInterval);
                    }
                },
                error: function(xhr, status, error) {
                    $('#taskStatus').show()
                        .find('.alert')
                        .removeClass('alert-info')
                        .addClass('alert-danger')
                        .text('获取任务状态失败：' + error);
                    clearInterval(progressInterval);
                }
            });
        }
        
        checkStatus();
    }

    function updateProgress(progress) {
        const $progressBar = $('.progress-bar');
        $progressBar.css('width', progress + '%')
                   .attr('aria-valuenow', progress)
                   .find('.progress-text').text(progress + '%');
    }

    // 取消任务
    $('.cancel-task').click(function() {
        const taskId = $(this).data('task-id');
        if (confirm('确定要取消该任务吗？')) {
            $.ajax({
                url: "{% url 'task_cancel' task_id='placeholder' %}".replace('placeholder', taskId),
                type: 'POST',
                data: {
                    csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
                },
                success: function(response) {
                    if (response.status === 'success') {
                        alert('任务已取消');
                        location.reload();
                    } else {
                        alert('取消任务失败：' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    alert('发生错误：' + error);
                }
            });
        }
    });
});
</script>
{% endblock %} 